package me.fung.rem.app.rem_editor

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import me.fung.keen.app.view.Presenter
import me.fung.keen.common.DataWrapper
import me.fung.rem.bean.database
import me.fung.rem.bean.repo.*
import me.fung.rem.common.PageState
import org.ktorm.entity.toList
import java.util.ArrayList

class RemEditorPresenter : Presenter() {
    val item = DataWrapper(RemItem.sample())
    val type = DataWrapper(PageState.BROWSE) // 浏览、修改、添加

    var pageState = mutableStateOf(PageState.BROWSE) // 页面状态
    var tags = mutableStateListOf<TagInfo>()

    fun load() {
        val a = database.tagInfoes.toList()
        tags.clear()
        tags.addAll(a)
    }

    fun update(block: RemItem.() -> RemItem) {
        item.update { item.data.block() }
    }

    fun addTag(it: TagInfo) {
        if (pageState.value in listOf(PageState.BROWSE)) return
        if (it.text in item.data.tags()) return
        val list = ArrayList<String>()
        list.addAll(item.data.tags())
        list.add(it.text)
        item.update { item.data.copy(tag = list.joinToString("|")) }
    }

    fun removeTag(it: String) {
        val list = item.data.tags().toMutableList()
        list.remove(it)
        item.update { item.data.copy(tag = list.tag()) }

    }

    fun save() {
        when (type.data) {
            PageState.BROWSE -> {}
            PageState.MODIFY -> {
                item.data.modify()
            }

            PageState.ADD -> {
                item.data.add()
            }
        }
    }

    fun delete() {
        item.data.delete()
    }
}